package com.dxy.lc.socketio.handler;

import com.dxy.lc.base.AppConstant;
import com.dxy.lc.enums.UserStatus;
import com.dxy.lc.model.bean.UserStateDto;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.service.SessionBindService;
import com.dxy.lc.service.UserService;
import com.dxy.lc.socketio.ISession;
import com.dxy.lc.socketio.ISessionService;
import com.dxy.lc.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class LcOnConnectEventHandler implements com.dxy.lc.socketio.OnConnectEventHandler {

    @Autowired
    private SessionBindService sessionBindService;
    @Autowired
    private UserService userService;
    @Autowired
    private ISessionService sessionService;

    @Override
    public void onConnect(ISession session) {
        // 获取userId
        String token = session.getConnectParam(AppConstant.QUERY_TOKEN_KEY);
        String userId = LoginUtil.getUserId(token);

        // 绑定用户、房间
        sessionBindService.bindSessionOnConnect(Integer.parseInt(userId), session.getSessionId());

        // 更新用户状态
        User u = new User()
                .setId(Integer.parseInt(userId))
                .setStatus(Integer.parseInt(UserStatus.ONLINE.toCode()));
        userService.updById(u);

        // 广播所有用户上线状态
        UserStateDto usd = new UserStateDto()
                .setUserId(Integer.parseInt(userId))
                .setUserStatus(UserStatus.ONLINE);
        sessionService.sendMessageToLoginUsers(AppConstant.SOCKET_EVENT_STATE, usd);
    }
}
